from PySide6.QtWidgets import QDialog,QMessageBox
from PySide6.QtCore import QDate
import datetime
from sqlalchemy.orm import Session
from views.person.work.opetrationjobinfo import Ui_operationjobinfo
from views.person.model.person import JobInfo,PersonBaseInfo
from settings.publicvar import engine

class OperationJobInfoView(QDialog,Ui_operationjobinfo):
    def __init__(self,is_status,data):
        super().__init__()
        self.setupUi(self)
        self.if_status(is_status)
        self.setFormStructure(data)

        self.addbtn.clicked.connect(self.addFun)
        self.name.editingFinished.connect(self.nameFinishedFun)
        self.deletebtn.clicked.connect(self.deleteFun)
        self.changebtn.clicked.connect(self.changeFun)


    # 状态判断
    def if_status(self,is_status):
        if is_status =='add':
            self.titlelable.setText('添加工作信息')
            self.IDcard.setText('身份证')
            self.name.setPlaceholderText('检查人员信息是否存在！')
            self.deletebtn.hide()
            self.changebtn.hide()
        elif is_status == 'change':
            self.titlelable.setText('修改工作信息')
            self.name.setDisabled(True)
            self.deletebtn.hide()
            self.addbtn.hide()
        elif is_status == 'view':
            self.titlelable.setText('查看工作信息')
            self.name.setDisabled(True)
            self.addbtn.hide()
            self.deletebtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
        else:
            self.titlelable.setText('删除工作信息')
            self.name.setDisabled(True)
            self.addbtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()

    # 设置表结构
    def setFormStructure(self,data):
        if data:
            self.idx.setText(data[0])
            self.name.setText(data[1])
            self.enter_unit.setText(data[2])
            self.transfer_out_unit.setText(data[3])
            date = QDate.fromString(data[4], "yyyy-MM-dd")
            if date.isValid():
                self.enter_date.setDate(date)
            else:
                self.enter_date.setDate(QDate(1, 1, 1))
                self.enter_date.setSpecialValueText("请选择日期")
            date = QDate.fromString(data[5], "yyyy-MM-dd")
            if date.isValid():
                self.transfer_out_date.setDate(date)
            else:
                self.transfer_out_date.setDate(QDate(1, 1, 1))
                self.transfer_out_date.setSpecialValueText("请选择日期")
            self.enter_exit_mode.setCurrentText(data[6])
            self.employment_status.setCurrentText(data[7])
            self.employment_type.setCurrentText(data[8])
            self.mark.setText(data[9])

    # 获取表单数据
    def get_from_data(self):
        idx = self.idx.text().strip()
        enter_unit = self.enter_unit.text().strip()
        transfer_out_unit = self.transfer_out_unit.text().strip()
        enter_date = self.enter_date.date()
        enter_date = datetime.date(enter_date.year(),enter_date.month(),enter_date.day())
        date = self.transfer_out_date.date()
        transfer_out_date = datetime.date(date.year(),date.month(),date.day())
        enter_exit_mode = self.enter_exit_mode.currentText()
        employment_status = self.employment_status.currentText()
        employment_type = self.employment_type.currentText()
        mark = self.mark.text().strip()

        data = {
            'enter_unit': enter_unit,
            'transfer_out_unit': transfer_out_unit,
            'enter_date': enter_date,
            'transfer_out_date': transfer_out_date,
            'enter_exit_mode': enter_exit_mode,
            'employment_status': employment_status,
            'employment_type': employment_type,
            'mark': mark
        }
        if idx =='':
            return [False,data]
        else:
            return [idx,data]

    def nameFinishedFun(self):
        IDcard = self.name.text().strip()
        with Session(engine) as session,session.begin():
            try:
                personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard == IDcard).one()
                if not personbase.personothers:
                    self.name.setText(personbase.name)
                    self.name_id = personbase.id
                else:
                    QMessageBox.critical(None, '失败', '数据已经增加了，不用添加！')
                    self.close()
            except:
                QMessageBox.critical(None,'失败','没有找到基本信息，请选增加基本信息,请检查身份证是否输错！')

    # 添加
    def addFun(self):
        data = self.get_from_data()
        if  ~data[0]:
            with Session(engine) as session,session.begin():
                data[1]['name_id'] = self.name_id
                jobinfo = JobInfo(**data[1])
                session.add(jobinfo)
                QMessageBox.information(None,'成功','恭喜，你添加的%s工作信息成功！'%self.name.text().strip())
        self.close()

    # 删除
    def deleteFun(self):
        data = self.get_from_data()
        with Session(engine) as session,session.begin():
            session.query(JobInfo).filter(JobInfo.id == data[0]).delete()
            QMessageBox.information(None, '成功', '恭喜，%s工作信息成功！' % self.name.text().strip())
        self.close()

    # 修改
    def changeFun(self):
        data = self.get_from_data()
        with Session(engine) as session,session.begin():
            session.query(JobInfo).filter(JobInfo.id == data[0]).update(data[1])
            QMessageBox.information(None,'成功','%s修改成功'%self.name.text().strip())
        self.close()